/*
	This file is part of GTimer.

    GTimer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License\.

    GTimer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with GTimer. If not, see <http://www.gnu.org/licenses/>.
	
	Copyright 2012 Muhammad Ghareeb Sideek
	Contact: MGhareeb64@gmail.com
 */

package com.gsourcecode.timer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gsourcecode.command.Command;
import com.gsourcecode.utils.Samples;

public class GTimerMain extends Activity {

	public static String gtimerFile;
	private File temp, settings, root;
	private ListView lstFiles;
	private Builder newGTimerAlert, openGTimerAlert;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		lstFiles = (ListView) findViewById(R.id.lstFiles);
		lstFiles.setOnItemClickListener(new ListListener());
		lstFiles.setFocusableInTouchMode(true);
		lstFiles.requestFocus();

		((Button) findViewById(R.id.btnSettings)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.SettingsActivity")));
				} catch (Exception e) {}
			}
		});
		((Button) findViewById(R.id.btnAbout)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Builder builder = new Builder(GTimerMain.this);
				TextView tv = new TextView(GTimerMain.this);
				tv.setText(R.string.about);
				tv.setAutoLinkMask(Linkify.EMAIL_ADDRESSES);
				tv.setMovementMethod(LinkMovementMethod.getInstance());
				tv.setTextSize(20f);
				builder.setView(tv);
				builder.show();
			}
		});
		// FILE NAME
		newGTimerAlert = new AlertDialog.Builder(this);
		newGTimerAlert.setTitle("Name your GTimer file");
		final EditText input = new EditText(this);
		input.setText("gtimer");
		newGTimerAlert.setView(input);
		newGTimerAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				gtimerFile = input.getText().toString();
				if (gtimerFile.length() != 0) {
					try {
						File f = new File(root.getAbsoluteFile() + File.separator + gtimerFile + ".txt");
						if (f.exists())
							Toast.makeText(GTimerMain.this, "A Gtimer file with this name already exisits!", Toast.LENGTH_LONG);
						else {
							f.createNewFile();
							if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
								startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.EditGTimer")));
							else
								startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.EditGTimer2")));
						}
					} catch (Exception e) {}
				} else
					Toast.makeText(GTimerMain.this, "Bad name!", Toast.LENGTH_LONG);
			}
		});
		// PLAY - EDIT - DELETE
		openGTimerAlert = new AlertDialog.Builder(this);
		openGTimerAlert.setTitle("Specify an action for the selected GTimer");
		// PLAY
		openGTimerAlert.setPositiveButton("Play", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				try {
					// convert
					String file = gtimerFile + ".txt";
					Toast.makeText(GTimerMain.this, "Loading \"" + file + "\"...", Toast.LENGTH_SHORT).show();
					ArrayList<Command> c = Command.parseFile(new File(root.getAbsolutePath() + File.separator + file));
					// serialize
					ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(temp));
					out.writeObject(c);
					out.close();
					// play
					if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
						startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.GTimerPlay")));
					else
						startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.GTimerPlay2")));
					finish();
				} catch (Exception e) {
					Toast.makeText(GTimerMain.this, getString(R.string.bad_file), Toast.LENGTH_LONG).show();
				}
			}
		});
		// EDIT
		openGTimerAlert.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				try {
					if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
						startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.EditGTimer")));
					else
						startActivity(new Intent(GTimerMain.this, Class.forName("com.gsourcecode.timer.EditGTimer2")));
				} catch (Exception e) {}
			}
		});
		// DELETE
		openGTimerAlert.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				Builder b = new AlertDialog.Builder(GTimerMain.this);
				b.setTitle("Delete \'" + gtimerFile + "\'? Are you sure?");
				b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							File f = new File(root.getAbsoluteFile() + File.separator + gtimerFile + ".txt");
							f.delete();
							onResume();
						} catch (Exception e) {}
					}
				});
				b.setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				});
				b.show();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (GTimerPlay.timer != null)
			GTimerPlay.timer.cancel();
		if (!prepareSDC())
			Toast.makeText(this, getString(R.string.no_sd), Toast.LENGTH_LONG).show();
		else if (!listFiles())
			Toast.makeText(this, getString(R.string.no_file) + " " + getString(R.string.file_hint), Toast.LENGTH_LONG).show();
		else if (!loadSettings())
			Toast.makeText(this, getString(R.string.no_settings) + " " + getString(R.string.file_hint), Toast.LENGTH_LONG).show();
	}

	// FILES

	private boolean listFiles() {
		try {
			ArrayList<String> fileList = new ArrayList<String>();
			fileList.clear();
			for (File file : root.listFiles())
				if (!file.isDirectory() && file.getName().indexOf(".txt") == file.getName().length() - 4)
					fileList.add(file.getName().substring(0, file.getName().length() - 4));
			fileList.add("New GTimer...");
			ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
			lstFiles.setAdapter(directoryList);
			return true;
		} catch (Exception e) {}
		return false;
	}

	private boolean prepareSDC() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "gtimer");
			temp = new File(root.getAbsolutePath() + File.separator + "temp");
			settings = new File(root.getAbsolutePath() + File.separator + "settings");
			// write
			try {
				if ((root.exists() && root.isDirectory()) || (root.mkdir() && Samples.flood(root)))
					if ((settings.exists() && settings.isFile()) || (settings.createNewFile() && initSettnigs()))
						if ((temp.exists() && temp.isFile()) || temp.createNewFile())
							return true;
			} catch (Exception e) {}
		}
		return false;
	}

	private boolean initSettnigs() {
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(settings));
			out.writeObject(Settings.get());
			out.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private boolean loadSettings() {
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(settings));
			Settings.set((Settings) in.readObject());
			in.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	// LISTENERS

	public class ListListener implements OnItemClickListener {

		public ListListener() {}

		public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
			if (lstFiles.getItemAtPosition(myItemInt).equals("New GTimer...")) {
				newGTimerAlert.show();
			} else {
				gtimerFile = lstFiles.getItemAtPosition(myItemInt).toString();
				openGTimerAlert.show();
			}
		}
	}
}
